/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package vn.webapp.controller.cp;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import vn.webapp.controller.BaseWeb;
import vn.webapp.dto.DataPage;
import vn.webapp.form.UserAddingValidationForm;
import vn.webapp.form.UserValidationForm;
import vn.webapp.model.Clas;
import vn.webapp.model.Classes;
import vn.webapp.model.Student;
import vn.webapp.model.User;
import vn.webapp.model.Users;
import vn.webapp.service.ClassesService;
import vn.webapp.service.StudentsService;
import vn.webapp.service.UserService;

@Controller("cpIndex")
@RequestMapping(value = {"/cp"})
public class IndexController extends BaseWeb {

    @Autowired
    private UserService userService;
    private Integer nav = 0;
    
    @Autowired
    private ClassesService classessService;

    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/actions", method = RequestMethod.GET)
    public String home(ModelMap model, HttpSession session) {
        this.nav = 7;
        model.put("nav", this.nav);
        return "cp.actions";
    }
    
    /**
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap model, HttpSession session, 
    @RequestParam(value = "page", defaultValue = "0") int page) {
        int pageSize = 10;        
        DataPage<Users> dataUser = userService.filter(page, pageSize);
        //DataPage<Users> dataUser = userService.list();
        model.put("dataUser", dataUser);
        model.put("sz_Response", session.getAttribute("response"));
        session.setAttribute("response", "");
        model.put("nav", this.nav);
        model.put("pageIndex", page);
        return "cp.index";
    }

    @RequestMapping("/userdetail/{id}")
    public String viewDetail(ModelMap model, @PathVariable("id") String id) {
        Users user = userService.viewDetail(id);
        model.put("userForm", new UserValidationForm());
        model.put("dataUser", user);
        model.put("nav", this.nav);
        return "cp.userdetail";
    }

    /**
     *
     * @param validationForm
     * @param result
     * @param model
     * @return
     */
    @RequestMapping(value = "/saveuserdetail", method = RequestMethod.POST)
    public String processValidatinForm(@Valid @ModelAttribute("userForm") UserValidationForm userForm,
            BindingResult result, Map model, HttpSession session) {
        
        // Add the saved validationForm to the model  
        model.put("nav", this.nav);
        if (result.hasErrors()) {
           return "cp.userdetail";
        }else
        {
            String username = userForm.getUsername();
            User o_Username = userService.loadUserByUsername(username);
            if(o_Username != null)
            {
                model.put("abc", username);
                return "cp.userdetail";
            }
        }
        session.setAttribute("response", "Edit successfully!");
        return "redirect:" + this.baseUrl + "/cp/index.html";
    }

    /**
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/removeuser/{id}", method = RequestMethod.GET)
    public String processRemoveUser(ModelMap model, @PathVariable("id") String id, HttpSession session) {
        int i_IsRemoved = userService.removeUser(id);
        String sz_Response;
        if (i_IsRemoved != 0) {
            sz_Response = "Remove the user successfully !";
        } else {
            sz_Response = "Remove the user not successfully. Please retry";
        }
        session.setAttribute("response", sz_Response);
        return "redirect:" + this.baseUrl + "/cp/index.html";
    }
    
    /**
     *
     * @param model
     * @param result
     * @return
     */
    @RequestMapping(value = "/addnewuser", method = RequestMethod.GET)
    public String addnewuser(Map model){
        model.put("nav", this.nav);
        model.put("userFormAdd", new UserAddingValidationForm());
        return "cp.addnewuser";
    }
    
    /**
     * 
     * @param userForm
     * @param result
     * @param model
     * @param session
     * @return 
     */
    @RequestMapping(value = "/saveuser", method = RequestMethod.POST)
    public String processAddNewUser(@Valid @ModelAttribute("userFormAdd") UserAddingValidationForm userFormAdd,
            BindingResult result, Map model, HttpSession session) {
        
        // Add the saved validationForm to the model  
        model.put("nav", this.nav);
        if (result.hasErrors()) {
            String sss = "sss";
           return "cp.addnewuser";
        }else
        {
            String username = userFormAdd.getUsername();
            User o_Username = userService.loadUserByUsername(username);
            if(o_Username != null)
            {
                model.put("sz_Response", "The username is exists.");
                //return "cp.addnewuser";
            }
            String salt = "abc-xyz-kmlnopq";
            String email = userFormAdd.getEmail();
            final String password = DigestUtils.md5Hex (userFormAdd.getPassword() + salt);
            
            int i_InsertUser = userService.saveAUser(username, password, salt, email);
        }
        session.setAttribute("response", "Add successfully!");
        return "redirect:" + this.baseUrl + "/cp/index.html";
    }
    
   @RequestMapping(value = "/testing", method = RequestMethod.GET)
    public String testOneToMany(ModelMap model, HttpSession session,
        @RequestParam(value = "page", defaultValue = "0") int page) {
        int pageSize = 10;        
        DataPage<Clas> dataClases = classessService.filterTesting(page, pageSize);
        List<Clas> cla = dataClases.getData();
        Set<Clas> dataCla = new HashSet<Clas>(cla);
        Set<Clas> dataClases1 = classessService.listTesting();
        model.put("dataClases", dataCla);
        model.put("pageIndex", page);
        model.put("pageCount", dataClases.getPageCount());
        
        return "cp.testing";
    }
    
}
